package com.pms.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pms.dao.SysUserDao;
import com.pms.entity.SysUser;
import com.pms.service.ISysUserService;
import com.pms.utils.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysUserService implements ISysUserService {
    private Log log = LogFactory.getLog(SysUserService.class);
    @Autowired
    private SysUserDao sysUserDao;

    @Override
    public SysUser findById(Integer id) {
        return sysUserDao.findById(id);
    }

    @Override
    public List<SysUser> findAll() {
        return sysUserDao.findAll();
    }

    @Override
    public void save(SysUser user) {
    }

    @Override
    public boolean update(SysUser user) {
        boolean flag = false;
        if (user != null && user.getId() != null && user.getId() > 0){
            try {
                sysUserDao.update(user);
                flag = true;
            }catch (Exception e){
            }
        }
        return flag;
    }

    @Override
    public void delete(Integer id) {
        sysUserDao.delete(id);
    }
    //0--密码错误，1--正常，-1--用户名不存在
    @Override
    public ReturnInfo checkLogin(User u) {
        ReturnInfo info = new ReturnInfo();
        SysUser user = sysUserDao.find(new SysUser(null, null, u.getLogin_name(), null, null));
        if (user == null) {
            info.setCode(-1);
            info.setMsg("用户名不存在");
        } else if (u.getLogin_pwd() == null || !u.getLogin_pwd().equals(user.getLogin_pwd())) {
            info.setCode(0);
            info.setMsg("密码错误，请重新输入");
        }else {
            info.setCode(1);
            info.setMsg("登陆成功，将跳转到主页");
            user.setLogin_pwd(null);
            info.setData(user);
        }
        return info;
    }

    @Override
    public SysUser find(SysUser user) {
        return sysUserDao.find(user);
    }

    @Override
    public List<SysUser> findPage() {
        return sysUserDao.findPage();
    }

    @Override
    public DataTableResponse findDataPage(DataTableRequest data) {
        PageUtil.checkRequestData(data);
        DataTableResponse result = new DataTableResponse();
        int page = PageUtil.getPageNum(data);
        PageHelper.startPage(page, data.getLength());
        List<SysUser> list = sysUserDao.findPage();
        System.out.println(list);
        PageInfo pages = new PageInfo(list);
        result.setData(list);
        result.setDraw(data.getDraw());
        result.setRecordsTotal((int)pages.getTotal());
        result.setRecordsFiltered((int)pages.getTotal());
        log.info("********** test2 : " + result);
        return result;
    }
}
